package com.bridge.common.http;

import android.content.Context;
import android.text.TextUtils;
import android.util.Log;

import com.bridge.common.intercepters.AddUrlInterceptor;
import com.bridge.common.intercepters.HeaderIntercepter;
import com.bridge.common.intercepters.LoggerIntercepter;
import com.bridge.common.utils.SpUtils;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.io.IOException;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLSession;

import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * http管理类
 */

public class HttpManager {
    public static String BASE_URL;
    public static long TIMEOUT;
    private static HttpManager httpManager;
    /*----------------------------------------------------------------------------------------------*/
    public static OkHttpClient httpClient;
    private static Context mContext;

    private HttpManager() {
    }

    public static HttpManager getInstance() {
        if (httpManager == null) {
            synchronized (HttpManager.class) {
                if (httpManager == null) {
                    httpManager = new HttpManager();
                }
            }
        }
        return httpManager;
    }

    /**
     * @param baseUrl
     * @param timeout 连接超时时间 秒
     * @param service 服务端通信接口
     **/
    public static <T> void init(String baseUrl, long timeout, Class<T> service, Context context) {
        TIMEOUT = timeout;
        mContext = context;
        BASE_URL = baseUrl;
        OkHttpClient.Builder builder = new OkHttpClient.Builder()
                .addInterceptor(new HeaderIntercepter())
                .addInterceptor(new AddUrlInterceptor()) //自定义拦截器加后缀信息
                .addInterceptor(new LoggerIntercepter())
                .addNetworkInterceptor(new TokenHeaderInterceptor())
                .hostnameVerifier(new HostnameVerifier() {
                    @Override
                    public boolean verify(String hostname, SSLSession session) {
                        return true;
                    }
                })
                .connectTimeout(TIMEOUT, TimeUnit.SECONDS)
                .readTimeout(TIMEOUT, TimeUnit.SECONDS);
        httpClient = builder.build();
    }

    public static <T> T getService(Class<T> tClass, String url) {
        return (T) new Retrofit.Builder()
                .baseUrl(url)
                .addConverterFactory(GsonConverterFactory.create(buildGson()))
                // 添加Retrofit到RxJava的转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient)
                .build()
                .create(tClass);
    }

    public static <T> T getService(Class<T> tClass) {
        return (T) new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(buildGson()))
                // 添加Retrofit到RxJava的转换器
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(httpClient)
                .build()
                .create(tClass);
    }

    private static Gson buildGson() {
        return new GsonBuilder()
                .serializeNulls()
                .setFieldNamingPolicy(FieldNamingPolicy.IDENTITY)
                // 此处可以添加Gson 自定义TypeAdapter
                //json转换null变""
//                .registerTypeAdapterFactory(new BaseBean.NullStringToEmptyAdapterFactory())
                .create();
    }

    /**
     * 获取请求体
     *
     * @return
     */
    public static RequestBody getRqBody(Map map, ReqOptions options) {
        MediaType type = MediaType.parse("application/json; charset=utf-8");
        //编解码,
        //之所以对gson这样初始化，而不是直接new Gson（）是因为在new Gson().toJson的时候会把"'"转成/u2007的形式
        Gson gson = new GsonBuilder().disableHtmlEscaping().create();
        RequestBody body = RequestBody.create(gson.toJson(map), type);
        return body;
    }

    public static class TokenHeaderInterceptor implements Interceptor {

        @Override
        public Response intercept(Chain chain) throws IOException {
            String token = SpUtils.getString(mContext, SpUtils.TOKEN, ""); //SpUtils是SharedPreferences的工具类，自行实现
            Log.e("Authorization", "Bearer "+token);
            if (token.isEmpty()) {
                Request originalRequest = chain.request();
                return chain.proceed(originalRequest);
            } else {
                Request originalRequest = chain.request();
                //key的话以后台给的为准，我这边是叫token
                Request updateRequest = originalRequest.newBuilder().header("Authorization", "Bearer "+token).build();
                return chain.proceed(updateRequest);
            }
        }
    }
}
